import React, {Component} from 'react' 
import logo from '../../assets/images/logo.png'
import { Form, Icon, Input, Button,message} from 'antd';
import {Redirect} from 'react-router-dom'
import './login.less'
import {reqLogin} from '../../api'
import memoryUtils from '../../utils/memoryUtils.js'
import storeUtils from '../../utils/storeUtils.js'



class Login  extends  Component{
  handleSubmit=(event)=>{
    event.preventDefault()
    this.props.form.validateFields(async (err, values) => {
      if (!err) {
        const {username,password} = values
                const result = await reqLogin(username,password)
                if(result.status===0){
                  message.success('登陆成功')
                  memoryUtils.user = result.data
                  storeUtils.saveUser(result.data)

                  this.props.history.replace('/')
                }else{
                  message.error(result.msg);
                }
           
          
      }else{
        console.log('校验失败')
      }
    });

  }
  validatPwd=(rule, value, callback)=>{
    if(!value){
      callback('请输入密码')
    }else if(value.length <= 4){
      callback('密码长度不可以小于4位')
    }else if(value.length >= 12){
      callback('密码长度不可以大于2位')
    }else if(!/^[a-zA-Z0-9_]+$/.test(value)){
      callback('密码必须是数字字母下划线组成')
    }
    else{
      callback()
    }
  }
  
 render(){
  const { getFieldDecorator } = this.props.form;

  if(memoryUtils.user && memoryUtils.user._id){
      return <Redirect to= '/' />
  }
  return (
    <div className="login">
    <header className='login-header'>
      <img src={logo} alt="logo" />
      <h1> React项目：后台管理系统</h1>
    </header>
    <section className="login-content">
      <h2>用户登录界面</h2>

          <Form onSubmit={this.handleSubmit} className="login-form">
        <Form.Item>
          {getFieldDecorator('username', {
            rules: [
              { required: true, whitespace:true, message: '用输入您的名字' },
              { min: 4, message: '用户名最少为4位' },
              { max: 12, message: '用户名最多不可以多于12位' },
              { pattern: /^[a-z0-9A-Z_]+$/, message: '用户名必须包含数字字母下划线' },
            ],
          })(
            <Input
              prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="用户名"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('password', {
            rules: [{validator: this.validatPwd}],
          })(
            <Input
              prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
              type="password"
              placeholder="密码"
            />,
          )}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">
           登陆
          </Button>
        </Form.Item>
      </Form>
      
    </section>
      
    </div>
  );
 }
 
}
export default  Form.create()(Login);

// export default Login;